<template>
  <transition :name="transitionName">
    <div v-if="visible" class="toast-container" :class="[type, position]">
      <i :class="['iconfont', iconClass]"></i>
      <span>{{ message }}</span>
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      message: '',
      type: 'info',
      position: 'top'
    }
  },

  computed: {
    iconClass() {
      return {
        'success': 'icon-success',
        'error': 'icon-error',
        'warning': 'icon-warning',
        'info': 'icon-info'
      }[this.type]
    },

    transitionName() {
      return this.position === 'top' ? 'slide-down' : 'fade'
    }
  },

  methods: {
    show(message, type = 'info', position = 'top', duration = 3000) {
      this.message = message
      this.type = type
      this.position = position
      this.visible = true

      setTimeout(() => {
        this.visible = false
      }, duration)
    }
  }
}
</script>

<style scoped lang="scss">
.toast-container {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  padding: 8px 16px;
  font-size: 0.32rem; /* 12px */
  min-width: auto;
  max-width: 70%;
  border-radius: 3px;

  .iconfont {
    font-size: 0.32rem;
    margin-right: 4px;
  }
}

&.top {
  top: 15%;
}

  &.success {
    background-color: #67c23a;
  }

  &.error {
    background-color: #f56c6c;
  }

  &.warning {
    background-color: #e6a23c;
  }

  &.info {
    background-color: #909399;
  }

  .iconfont {
    margin-right: 8px;
    font-size: 16px;
  }
}

.slide-down-enter-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-down-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-down-enter,
.slide-down-leave-to {
  transform: translate(-50%, -20px);
  opacity: 0;
}
</style>